package io.zhengsh.jmm;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

class MyData {
    volatile int number = 0;

    public void addTo60() {
        this.number = 60;
    }



    public synchronized void addPlusPlus() {
        this.number++;
    }
}

public class VolatileDemo {

    public static void main(String[] args) throws InterruptedException {
        MyData myData = new MyData();
        for (int i = 0; i < 20; i++) {
            new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    myData.addPlusPlus();
                }
            }, "T" + i).start();
        }
        while (Thread.activeCount() > 2) {
            Thread.yield();
        }
        System.out.println(myData.number);
    }

    private static void v1() {
        MyData myData = new MyData();

        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "\t 进入");
            /*
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
             */
            myData.addTo60();
            System.out.println(Thread.currentThread().getName() + "\t 更新");
        }, "AAA");

        while (myData.number == 0) {

        }
        System.out.println(Thread.currentThread().getName() + "\t 修改后的值是: " + myData.number);
    }
}
